<template>
  <a-modal :width="1200" v-model:visible="showHandleDeliveryOrder" title="确认交货单" top="8vh" title-align="start" :footer="false" :mask-closable="false" @cancel="closedDialog">
    <div class="order-w flex">
      <div class="order-detail-item" style="width: 300px">
        <p>
          <span class="label">交货单号：</span>
          <span class="highlight">{{ currentItem.billNo }}</span>
        </p>
        <p>
          <span class="label">目的仓库：</span>
          <span>{{ currentItem.warehouseName }}({{ currentItem.warehouseCode }})</span>
        </p>
      </div>
      <div class="order-detail-item" style="width: 300px">
        <p><span class="label">供应商：</span>{{ currentItem.supplierName }}({{ currentItem.supplierCode }})</p>
        <p><span class="label">交货日期：</span>{{ $setTime(currentItem.gmtDelivery, 'YYYY/MM/DD HH:mm') }}</p>
      </div>
      <div class="order-detail-item" style="width: 300px">
        <p><span class="label">创建人：</span>{{ currentItem.createUname }}</p>
        <p><span class="label">创建时间：</span>{{ $setTime(currentItem.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
      </div>
    </div>
    <a-table class="table-two-line" ref="tableRef" row-key="id" :data="purchaseOrders" :scroll="{ y: 'calc(84vh - 200px)' }" :columns="tableColumns" size="mini" :bordered="false" :pagination="false">
      <template #columns>
        <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
          <template v-if="item.dataIndex == 'num'" #title>
            <p>
              <span class="warningColor">*</span>
              <span>实际交货数</span>
            </p>
          </template>
          <template v-if="item.dataIndex == 'purchaseNo'" #cell="{ record }">
            <p class="highlight">{{ record.purchaseNo }}</p>
          </template>
          <template v-else-if="item.dataIndex == 'img'" #cell="{ record }">
            <ImgPopover :src="record.productImg">
              <template #con>
                <a-image width="40" height="40" fit="contain" :src="record.productImg" />
              </template>
            </ImgPopover>
          </template>
          <template v-else-if="item.dataIndex == 'productName'" #cell="{ record }">
            <TextLimit :val="record.productName" />
          </template>
          <template v-else-if="item.dataIndex == 'sku'" #cell="{ record }">
            <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
            <p>{{ record.cateName || '--' }}</p>
          </template>
          <template v-else-if="item.dataIndex == 'productSpecs'" #cell="{ record }">
            <TextLimit :val="getProductSpecs(record)" />
          </template>
          <template v-else-if="item.dataIndex == 'num'" #cell="{ record }">
            <a-input-number :min="0" :precision="0" v-model="record.num" style="width: 90px" placeholder="" />
          </template>
          <template v-else-if="item.dataIndex == 'diff'" #cell="{ record }">
            <p>{{ Number(record.deliveryAmt || 0) - Number(record.num || 0) }}</p>
          </template>
          <template v-else-if="item.dataIndex == 'price'" #cell="{ record }">
            <p class="price-type highlight">{{ record.priceType === 1 ? '含税' : '不含税' }}</p>
            <p>￥{{ record.price }}</p>
          </template>
          <template v-else-if="item.dataIndex == 'deliveryValue'" #cell="{ record }">
            <p class="price-type highlight">{{ record.priceType === 1 ? '含税' : '不含税' }}</p>
            <p>￥{{ (Number(record.num || 0) * Number(record.price || 0)).toFixed(2) }}</p>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <div class="handle-w">
      <a-button @click="closedDialog">取消</a-button>
      <a-popconfirm :on-before-ok="reject" :ok-loading="rejectLoading" @popup-visible-change="signRemark = ''">
        <template #content>
          <p style="margin-bottom: 10px">请输入拒绝理由</p>
          <a-textarea v-model="signRemark" style="width: 260px; height: 100px" placeholder="请输入拒绝理由" allow-clear />
        </template>
        <a-button>拒绝签收</a-button>
      </a-popconfirm>

      <a-button type="primary" :submitLoading="submitLoading" @click="submitData">确认</a-button>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { signDeliveryOrder } from '@/api/purchase'
  import { parseJson } from '@/utils'

  onMounted(async () => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })
  const tableColumns: Array<any> = [
    {
      title: '采购单',
      dataIndex: 'purchaseNo',
      width: 100,
    },
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      width: 100,
    },
    {
      title: 'SKU/类目',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: 'SKU规格',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: '交货数',
      dataIndex: 'deliveryAmt',
      width: 70,
    },
    {
      title: '实际交货数',
      dataIndex: 'num',
      width: 110,
    },

    {
      title: '交货差额',
      dataIndex: 'diff',
      width: 80,
    },
    {
      title: '采购单价',
      dataIndex: 'price',
      width: 80,
    },
    {
      title: '实交货值',
      dataIndex: 'deliveryValue',
      width: 80,
    },
  ]

  const showHandleDeliveryOrder = ref(props.isShow)
  const purchaseOrders = ref<Array<any>>([])
  const submitLoading = ref(false)
  const rejectLoading = ref(false)
  const signRemark = ref()

  // 添加初始化数据
  async function setDefaultData() {
    console.log(props.currentItem)
    purchaseOrders.value = props.currentItem.billItems?.map((el: any) => {
      return {
        ...el,
        num: el.deliveryAmt,
      }
    })
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 关闭
  function closedDialog() {
    showHandleDeliveryOrder.value = false
    emit('closed')
  }
  // 拒绝
  async function reject() {
    if (!signRemark.value) {
      Message.error('请输入拒绝签收原因！')
      return false
    }
    const res: any = await signDeliveryOrder({
      id: props.currentItem?.id,
      signRemark: signRemark.value,
      pass: false,
    })
    if (!res) return false
    Message.success('已拒签')
    emit('success')
    closedDialog()
  }
  // 判断空
  function isNull(val: any) {
    return val === undefined || val === null || val === ''
  }
  // 保存
  async function submitData() {
    let flag = false
    let purchaseItems: Array<any> = []
    purchaseOrders.value.forEach((el: any) => {
      let obj = {
        id: el.id,
        deliveryRealAmt: el.num,
      }
      purchaseItems.push(obj)
      if (isNull(el.num)) flag = true
    })
    if (flag) {
      Message.error('实际入库数必填')
      return false
    }
    submitLoading.value = true
    const res: any = await signDeliveryOrder({
      id: props.currentItem?.id,
      pass: true,
      purchaseItems: purchaseItems,
    })
    submitLoading.value = false
    if (!res) return false
    Message.success('签收成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .order-w {
    padding: 10px;
    background-color: var(--color-neutral-2);
    color: #666;
    margin-bottom: 10px;
    .order-detail-item {
      width: 200px;
    }
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
  .handle-w {
    text-align: right;
    .arco-btn {
      margin-left: 20px;
    }
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
</style>
